#encoding=utf-8
#author=GreySign
#date=2010-7-29
#file=esxi_manage.py
#version=1.1
#update: 
#	[2010-9] 更新-i参数帮助安装sdk的关联模块
'''
用于管理esxi主机的vmware系统
基于vmware-cmd进行封装，可以使用-i参数进行vmware-cmd的环境安装，然后下载个vmware-cmd安装即可。
提供vmware-cmd的python接口
'''
import os
from optparse import OptionParser
import sys
from outputhandle import DebugHandle


logfile = 'esxi_manage.log'
loglevel = 1 
PRINTER_LEVEL = 1
#初始化一个调试处理对象
dh = DebugHandle(logfile,loglevel,PRINTER_LEVEL)
printer = dh.printer

class EsxiManage(object):
	'''用于连接esxi主机，获得vmware信息'''
	def __init__(self,esxi_ip,username,passwd):
		''''''

		#esxi主机连接设置
		self.ip = esxi_ip
		self.username = username 
		self.passwd = passwd
		#连接esxi测试
		self.command = '/usr/bin/vmware-cmd -H %s -U %s \
		-P %s '%(self.ip,self.username,self.passwd)
		self.vms = self._get_vms()


	#----------------------------------------------------------------------
	def _get_vms(self):
		""""""
		cmd = self.command + '-l'
		#printer('get vms:',cmd)
		cmd_result = os.popen(cmd).read()
		vmlist = cmd_result.split()
		if vmlist:
			vm_objs = []
			for vm_cfg in vmlist:
				vm_objs.append(VmwareObj(self.ip,vm_cfg,self.command))
			return vm_objs
		else:
			return []
			
	def print_vms(self):
		for vm in self.vms:
			printer('get vm:',vm.name,vm.get_state())
			printer('cfg:',vm.cfg)
			printer('-'*60)





########################################################################
class VmwareObj(object):
	""""""

	#----------------------------------------------------------------------
	def __init__(self,esxi_ip,cfg,command):
		"""Constructor"""
		self.esxi_ip = esxi_ip
		self.cfg = cfg
		self.name = self._get_vm_name(cfg) 
		self.command = command + '"' + self.cfg + '" '
		#self.state = self.get_state()

	#----------------------------------------------------------------------
	def _get_vm_name(self,cfg):
		"""获取虚拟机名"""
		cfg_name = self.cfg.split('/')[-1]
		vm_name = cfg_name.split('.')[0]
		return vm_name


	#----------------------------------------------------------------------
	def get_state(self):
		"""获取vm的运行状态"""
		cmd = self.command + 'getstate'
		try:
			state = os.popen(cmd).read().strip()
			printer('%s %s!'%(self.name,state))
		except Exception,e:
			printer('get state error',str(e),pl=0,ltype='warning')
			return False
		return True

	#----------------------------------------------------------------------
	def start(self):
		"""
		powers on or resumes a VM.
		"""
		cmd = self.command + 'start'
		try:
			status = os.popen(cmd).read()
			printer('%s to start!'%(self.name))
		except Exception,e:
			printer('%s start error'%self.name,str(e),pl=0,ltype='warning')
			return False
		return True

	#----------------------------------------------------------------------
	def stop(self,powerop_mode='soft'):
		"""
		停止 VM. <powerop_mode> can be soft, hard.
		"""
		powerop_mode = str(powerop_mode)
		if mode == 'soft' or 'hard':
			cmd = self.command + 'stop ' + powerop_mode
		else:
			printer('powerop mode is error! can be soft,hard,not %s'%str(powerop_mode),pl=0,ltype='error')
			return False
		try:
			status = os.popen(cmd).read()
			printer('%s to stop!'%(self.name))
		except Exception,e:
			printer('%s stop error'%self.name,str(e),pl=0,ltype='error')
			return False
		return True        

	#----------------------------------------------------------------------
	def reset(self,powerop_mode='soft'):
		"""
		重置 VM. <powerop_mode> can be soft, hard.
		"""
		powerop_mode = str(powerop_mode)
		if mode == 'soft' or 'hard':
			cmd = self.command + 'reset ' + powerop_mode
		else:
			printer('powerop mode is error! can be soft,hard,not %s'%str(powerop_mode),pl=0,ltype='error')
			return False
		try:
			status = os.popen(cmd).read()
			printer('%s to reset!'%(self.name))
		except Exception,e:
			printer('%s reset error!'%self.name,str(e),pl=0,ltype='error')
			return False
		return True            

	#----------------------------------------------------------------------
	def suspend(self):
		"""
		挂起 VM. <powerop_mode> can be soft, hard.
		"""
		powerop_mode = str(powerop_mode)
		if mode == 'soft' or 'hard':
			cmd = self.command + 'suspend ' + powerop_mode
		else:
			printer('powerop mode is error! can be soft,hard,not %s'%str(powerop_mode),pl=0,ltype='error')
			return False
		try:
			status = os.popen(cmd).read()
			printer('%s to suspend!'%(self.name))
		except Exception,e:
			printer('%s suspend error!'%self.name,str(e),pl=0,ltype='error')
			return False
		return True     

	#----------------------------------------------------------------------
	def set_guestinfo(self,variable,value):
		"""
		sets a guest info variable
		"""
		variable = str(variable)
		value = str(variable)
		cmd = self.command + 'setguestinfo ' + variable + ' ' + value
		try:
			status = os.popen(cmd).read()
			printer('%s to set guest info!\nvariable is %s,value is %s...'%(self.name,variable,value))
		except Exception,e:
			printer('%s set guest info error!(variable:%s,value:%s)'%(self.name,variable,value),\
					str(e),pl=0,ltype='warning')
			return False
		return True 

	#----------------------------------------------------------------------
	def get_guestinfo(self,variable):
		"""
		retrieves the value for a guest info variable
		"""
		variable = str(variable)
		cmd = self.command + 'getguestinfo ' + variable
		try:
			status = os.popen(cmd).read()
			printer('%s to get guest info!\nvariable is %s...'%(self.name,variable))
		except Exception,e:
			printer('%s get guest info error!(variable:%s)'%(self.name,variable),\
					str(e),pl=0,ltype='warning')
			return False
		return True         

	#----------------------------------------------------------------------
	def get_productinfo(self,prodinfo="product"):
		"""
		获取产品信息。
		<prodinfo> can be product, platform, build, majorversion or minorversion
		"""
		prodinfo = str(prodinfo)
		if not prodinfo in ('product','platform','build','majorversion','minorversion'):
			return False
		cmd = self.command + 'getproductinfo ' + prodinfo
		try:
			status = os.popen(cmd).read()
			printer('%s to get guest productinfo!'%(self.name))
		except Exception,e:
			printer('%s get guest productinfo error!'%(self.name),\
					str(e),pl=0,ltype='warning')
			return False
		return status

	#----------------------------------------------------------------------
	def get_configfile(self):
		"""
		获取配置文件路径
		"""
		cmd = self.command + 'getconfigfile'
		try:
			status = os.popen(cmd).read()
			printer('%s to get guest configfile!'%(self.name))
		except Exception,e:
			printer('%s get guest configfile error!'%(self.name),\
					str(e),pl=0,ltype='warning')
			return False
		return status

	#----------------------------------------------------------------------
	def get_uptime(self):
		"""
		获取虚拟机开启时间
		"""
		cmd = self.command + 'getuptime'
		try:
			status = os.popen(cmd).read()
			printer('%s to get guest uptime!'%(self.name))
		except Exception,e:
			printer('%s get guest uptime error!'%(self.name),\
					str(e),pl=0,ltype='warning')
			return False
		return status

	#----------------------------------------------------------------------
	def get_tools_last_active(self):
		"""
		获取虚拟机里的vmtools状态
		"""
		cmd = self.command + 'gettoolslastactive'
		try:
			status = os.popen(cmd).read()
			printer('%s to get guest tools last active!'%(self.name))
		except Exception,e:
			printer('%s get guest tools last active error!'%(self.name),\
					str(e),pl=0,ltype='warning')
			return False
		return status

	#----------------------------------------------------------------------
	def has_snapshot(self):
		"""
		判断虚拟机是否有快照
		"""
		cmd = self.command + 'hassnapshot'
		try:
			status = os.popen(cmd).read()
			printer('%s to get guest has snapshot status!'%(self.name))
		except Exception,e:
			printer('%s get guest has snapshot status error!'%(self.name),\
					str(e),pl=0,ltype='warning')
			return False
		return status

	#----------------------------------------------------------------------
	def create_snapshot(self,name,description='',quiesce=0,memory=1):
		"""
		创建虚拟机快照
		quiesce will quiesce file system writes 
		memory ：Memory will grab the memory state (will lose pings during this) 
		"""
		name = str(name)
		if not description:
			description = '"esxi_manage.py auto create" '
		else:
			description = '"' + str(description) + '" '
		if quiesce:
			quiesce = '1'
		else:
			quiesce = '0'
		if memory:
			memory = '1'
		else:
			memory = '0'
		cmd = self.command + 'createsnapshot ' + name + ' ' + \
		    description + ' '+ quiesce + ' ' + memory
		try:
			printer(cmd)
			status = os.popen(cmd).read()
			printer('%s to create snapshot!'%(self.name))
		except Exception,e:
			printer('%s create snapshot error!'%(self.name),\
					str(e),pl=0,ltype='warning')
			return False
		return True

	#----------------------------------------------------------------------
	def revert_snapshot(self):
		"""
		将VM恢复到最后一次快照的状态
		"""
		cmd = self.command + 'revertsnapshot'
		try:
			status = os.popen(cmd).read()
			printer('%s to revert snapshot!'%(self.name))
		except Exception,e:
			printer('%s revert snapshot error!'%(self.name),\
					str(e),pl=0,ltype='warning')
			return False
		return True

	#----------------------------------------------------------------------
	def remove_snapshots(self):
		"""
		删除VM的所有快照
		"""
		cmd = self.command + 'removesnapshots'
		try:
			status = os.popen(cmd).read()
			printer('%s to remove all snapshots!'%(self.name))
		except Exception,e:
			printer('%s remove all snapshots error!'%(self.name),\
					str(e),pl=0,ltype='warning')
			return False
		return True        



if __name__ == '__main__':
	parser = OptionParser()
	parser.add_option("-i", "--install", dest="install", action="store_true",
		              default=False,
		              help="install vmware-cmd need software environment.")

	(options, args) = parser.parse_args()       
	if options.install:
		os.system('sudo apt-get install libcrypt-ssleay-perl')
		os.system('sudo apt-get install perl-doc')
		os.system('sudo apt-get install libssl-dev')
		os.system('sudo apt-get install libxml-libxml-perl')
		printer('install end.please install vmware-cmd and sudo chmod +x  /usr/bin/vmware-cmd ')
	else:
		print 'usage: python esxi_manage.py -i'

